import { getDetailsApi } from "@/api/waybillManagement/quotationApproval";
import { message } from "ant-design-vue";
import { cloneDeep } from "lodash";
import { computed, reactive, Ref, ref } from "vue";

export default function InitHook(state: {
  emit: {
    (e: "update:visible", blo: boolean): void;
    (e: "submit"): void;
    (e: "reject"): void;
  };
  searchData: Ref<() => QuotationApproval.SearchParams>;
}) {
  const { emit, searchData } = state;
  const formState = ref<any>({
    bizPreOrderShipmentResDto: {},
    bizOrderShipmentQuotation: {},
    bizOrderShipmentCosts: [],
    addCosts: [],
    freightCost: {
      opType: "1",
      adjustUnitPrice: 0,
      unitPrice: 0,
      clearingUnitPrice: 0,
      adjustReason: ""
    },
    totalFreightPrice: 0,
    totalFreightPriceStr: "",
    totalAdjustPrice: 0,
    totalAdjustPriceStr: "",
    totalAppendCostPrice: 0,
    totalAppendCostPriceStr: "",
    totalPrice: 0,
    totalPriceStr: ""
  });
  const loading = ref<boolean>(false);
  const dialogOpts = reactive<Base.DialogOpts>({
    title: "修改送货仓库",
    width: "720px",
    type: 1,
    passData: {},
    component: "",
    visible: false
  });
  const drawerOpts = reactive<Base.DrawerOpts>({
    title: "修改送货仓库",
    width: "720px",
    type: 1,
    passData: {},
    component: "",
    visible: false
  });
  // 有报价ID
  const init = (id: string, selectNext?: boolean, search?: any) => {
    loading.value = true;
    return getDetailsApi({ id, selectNext: selectNext ? selectNext : false, ...search })
      .then((res: any) => {
        const { code, data } = res;
        if (code === 200) {
          if (data) {
            formState.value = data;
            formState.value.freightCost = data.freightCost;
            if (formState.value.freightCost.adjustUnitPrice > 0) {
              formState.value.freightCost.opType = "1";
            } else {
              formState.value.freightCost.opType = "2";
            }
          } else {
            message.info("已经是最后一条数据!");
            emit("submit");
          }
        }
      })
      .finally(() => {
        loading.value = false;
      });
  };
  // 追加合计
  const addCostsCpt = computed<number>(() => {
    const allAddCosts = formState.value.addCosts?.map((t: any) => t.totalPrice || 0);
    return allAddCosts?.reduce((a: number, b: number) => a + b, 0) || 0;
  });
  const search = ref<QuotationApproval.SearchParams>(cloneDeep(searchData.value()));

  return {
    formState,
    loading,
    dialogOpts,
    drawerOpts,
    init,
    addCostsCpt,
    search
  };
}
